package com.demo.chapter6collect;

import java.util.Comparator;
import java.util.stream.IntStream;

import com.demo.domain.Dish;

import static java.util.stream.Collectors.*;

public class PartitionDemo {
	
	public static void demo(){
		//分区：只有2个区，true或false
		//按是否素食分区
		System.out.println(Dish.menu.stream().collect(partitioningBy(Dish::isVegetarian)));
	}
	
	public static void demo2(){
		//分区：可以传递第二个收集器，生成二级map
		System.out.println(Dish.menu.stream().collect(partitioningBy(Dish::isVegetarian, groupingBy(Dish::getType))));
		System.out.println(Dish.menu.stream().collect(partitioningBy(Dish::isVegetarian, counting())));
	}
	
	public static void demo3(){
		//分区：找到素食和非素食中热量最高的菜
		System.out.println(Dish.menu.stream().collect(partitioningBy(Dish::isVegetarian, maxBy(Comparator.comparing(Dish::getCalories)))));
	}
	
	//判断是否是质数
	private static boolean isPrime(int candidate){
		//candidate不能被2到candidate-1的任何数字整除，那么candidate就是质数
		return IntStream.range(2, candidate).noneMatch(i -> candidate % i == 0);
	}
	
	//把前n个自然数按质数非质数分区
	public static void demo4(int n){
		//把数字按质数和非质数分区
		System.out.println(IntStream.rangeClosed(1, n).boxed().collect(partitioningBy(candidate -> isPrime((int)candidate))));
	}
	
	public static void main(String[] args) {
		demo();
		demo2();
		demo3();
		demo4(100);
	}

}
